package com.ly.count.interceptor;

import cn.hutool.json.JSONUtil;
import com.ly.count.CPlusConstants;
import com.ly.count.context.CPlusLoginContext;
import com.ly.count.holder.TokenHolder;
import com.ly.count.utils.LoginContextUtil;
import com.ly.count.utils.ResponseModelUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Arrays;

public class CPlusLoginInterceptor implements HandlerInterceptor {

    public static final String [] WITHOUT_LOGIN_URL = new String[]{"/register","/login","loginOut"};
    Logger logger = (Logger) LogManager.getLogger(CPlusLoginInterceptor.class);
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        String path = request.getRequestURL().toString();
        if(path.contains(CPlusConstants.CPLUS_INTERFACE_FOR_WITHOUILOGIN) &&  Arrays.stream(WITHOUT_LOGIN_URL).anyMatch(path::contains) ){
            return true;
        }
        String token  = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            logger.info("token is null");
            sendErrorResponse(response);
            return false;
        }
        TokenHolder.setToken(token);
        CPlusLoginContext c = LoginContextUtil.getLoginContext();

        if(c == null){
            logger.info("CPlusLoginContext is null");
            TokenHolder.removeToken();
            sendErrorResponse(response);
            return false;
        }
        return true;
    }


    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        logger.info("postHandle is do nothing");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

        logger.info("afterCompletion remove token {0}",TokenHolder.getToken());
        TokenHolder.removeToken();
    }


    private void sendErrorResponse(HttpServletResponse response) throws IOException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSONUtil.toJsonStr(ResponseModelUtils.fail()));
    }

}
